import { ToastAndroid } from 'react-native'
import config from '../config'
import { objToUrl } from './index'
import { getToken, tokenStatus, refreshToken, checkTokenExpire } from './token'


export default async function request(option) {

  let url = generateUrl(option.path)

  let createdOption = createOption(option, url)
  let requestOption = createdOption.requestOption
  url = createdOption.url
  // 返回promise
  return new Promise(function(resolve, reject) {
    // 查看是否有token
    getToken().then(token => {
      let tokenStatus = checkTokenExpire(token)
      if(tokenStatus === 1) {
        // 刷新TOKEN
        refreshToken(token.token).then(newToken => {
          if(option.method === 'post') {
            url += '?token=' + newToken
          } else {
            url += '&token=' + newToken
          }

          resolve(getRequest(requestOption, url))
        })
      } else if(tokenStatus === 2) {
        // TOKEN已失效
        resolve(getRequest(requestOption, url))
      } else {
        if(option.method === 'post') {
          url += '?token=' + token.token
        } else {
          url += '&token=' + token.token
        }
        resolve(getRequest(requestOption, url))
      }
    }).catch(err => {
      resolve(getRequest(requestOption, url))
    })
  })
  
}

/**
*  请求接口
*  发生错误则处理错误
*  请求成功则返回接口数据
*/
export function getRequest(requestOption, url) {
  return new Promise(function(resolve, reject) {
    fetch(url, requestOption)
      .then(response => response.json())
      .then(data => {
        if(typeof (data.success) === 'undefined') {
          // 非后台接口
          resolve(data)
        } else if(!data.success) {
          ToastAndroid.show(data.message, ToastAndroid.SHORT)
        } else {
          resolve(data.data)
        }

      }).catch(err => {
        ToastAndroid.show('请求超时', ToastAndroid.SHORT)
      })
  })
}

// 生成接口地址
export function generateUrl(path) {
  if(path.substr(0, 4) === 'http') {
    return path
  }
  
  let midChar = ''
  if(
    config.api_url.substr(config.api_url.length - 1, 1) !== '/'
    && path.substr(0, 1) !== '/'
  ) {
    midChar = '/'
  }

  let url = config.api_url + midChar + path

  return url
}

// 生成请求设置
export function createOption(option, url) {
  let requestOption;
  if(option.method === 'post') {
    requestOption = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: objToUrl(option.data)
    }
  } else if(option.method === 'file') {
    // 文件上传请求，使用FormData对象发送数据
    let data = new FormData()
    for (const key in option.data) {
      data.append(key, option.data[key])
    }
    requestOption = {
      body: data
    }
    // 请求改为post
    option.method = 'post'
  } else {
    url += '?' + objToUrl(option.data)
    requestOption = {}
  }

  requestOption['method'] = option.method

  return { requestOption: requestOption, url: url }
}
